package oj_leetcode;

import java.util.HashMap;
import java.util.Map;

public class TwoSum {

    public int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        for (int i = 0; i < length - 1; i++) {
            for (int j = i + 1; j < length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    public int[] twoSumImproved(int[] nums, int target) {
        int length = nums.length;
        Map<Integer, Integer> num2Index = new HashMap<>();
        for (int i = 0; i < length; i++) {
            int currNum = nums[i];
            int complement = target - currNum;
            if (num2Index.containsKey(complement)) {
                return new int[]{num2Index.get(complement), i};
            }
            num2Index.put(currNum, i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
